package bairui.international.weixin.portal.miniapp.controller.order.product;

import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lianjing.sh.spring.web.controller.base.action.Action;
import com.lianjing.sh.spring.web.controller.enhance.output.FomatOutput;
import com.lianjing.sh.validate.spring.exception.ValidateObjectException;

import bairui.international.model.domain.jpa.TB_Product;
import bairui.international.model.domain.jpa.TB_ProductOrder;
import bairui.international.model.domain.jpa.TB_User;
import bairui.international.service.Service_ProductOrder;
import bairui.international.service.Service_ProductOrder.InputForCreate;
import bairui.international.service.Service_User;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

/**
 *
 * 创建易物订单
 *
 * @generated
 * 
 * @see STest_C_Order_Product_CreateCore_Post 测试
 *
 */
@Controller
public class C_Order_Product_CreateCore_Post
 extends SC_Order_Product_CreateCore_Post 
{
	
	@Autowired private Service_User service_User;
	@Autowired private Service_ProductOrder service_ProductOrder;
	
	/**
	 * Post请求
	 */
	@Action(Post.class)
	@PostMapping(Post.RequestMappingValue)
	public @FomatOutput @ResponseBody Object post(
		ModelMap map, HttpServletRequest request,
		@RequestParam String skey,
		@RequestBody List<Input> inputs
	) throws Exception {
		TB_User user = service_User.findOne(it->it.skey.eq(skey));
		if(null == user){
			return new Output(null, Output.State.Invalid);
		}
		// 验证
		if(inputs.isEmpty()){
			throw new ValidateObjectException("object", "", "订单内容不能为空");
		}
		// 创建订单
		TB_ProductOrder order = service_ProductOrder.createGradeOrder(
				user, 
				inputs
					.stream()
					.map(it->new InputForCreate(new TB_Product(it.getId()), it.getAmount()))
					.collect(Collectors.toList())
			);
		//
		return new Output(order.getId(), Output.State.OK);
	}
	
	private static class Input {
		@Getter @Setter private Long id;
		@Getter @Setter private Long amount;
	}
	
	@AllArgsConstructor
	private static class Output {
		
		public enum State {
			OK, Invalid
		}
		
		@Getter private Long id;
		@Getter private State state;	
	}

}
